import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.Border;

import org.jdesktop.swingx.JXDatePicker;

import CustomSwing.JCLabel;
import CustomSwing.TableColumnAdjuster;

@SuppressWarnings("serial")
public class MarketTotalsPanel extends JPanel {
	public String USER_FUNC = "Market Totals";
	private Font custFont = new Font("Arial Bold", Font.BOLD, 15);
	
	private Db db;
	private String dateStart;
	private String dateEnd;
	private JXDatePicker datePickerStart = new JXDatePicker();
	private JXDatePicker datePickerEnd = new JXDatePicker();
	private JRadioButton sortByTypeRB;
	private JRadioButton sortByDateRB;
	private JRadioButton sortByVendorRB;
	private ButtonGroup sortByBG = new ButtonGroup();
	
	private String[] columnNamesType = {"Date", "Plants", "Produce", "Processor", 
			"Prep. Food", "Crafter", "Reseller", "Total", "Running Total"};
	private String[] columnNamesDateOrVendor = {"Vendor ID", "Business Name", 
			"Sale Date", "Total"};
	private String[][] data;
	private JTable table;
	private JScrollPane tableSP;
	private JPanel tableSPPanel = new JPanel(new BorderLayout());
	
	public MarketTotalsPanel(Db theDB) {
		db = theDB;
		setDatePicker(datePickerStart, true);
		setDatePicker(datePickerEnd, false);
		
		Border b = BorderFactory.createCompoundBorder(
				BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK), 
				BorderFactory.createEmptyBorder(3, 3, 3, 3));
		
		JPanel startDatePanel = new JPanel(new GridLayout(2, 1));
		startDatePanel.setBorder(b);
		startDatePanel.add(new JCLabel("Start Date"));
		startDatePanel.add(datePickerStart);
		
		JPanel endDatePanel = new JPanel(new GridLayout(2, 1));
		endDatePanel.setBorder(b);
		endDatePanel.add(new JCLabel("End Date"));
		endDatePanel.add(datePickerEnd);
		
		sortByTypeRB = setSortByRB("Type");
		sortByDateRB = setSortByRB("Date");
		sortByVendorRB = setSortByRB("Vendor");
		JPanel rbPanel = new JPanel(new GridLayout(1, 3));
		rbPanel.add(sortByTypeRB);
		rbPanel.add(sortByDateRB);
		rbPanel.add(sortByVendorRB);
		
		JPanel sortByPanel = new JPanel(new BorderLayout());
		sortByPanel.setBorder(b);
		sortByPanel.add(new JCLabel("Sort By:"), BorderLayout.NORTH);
		sortByPanel.add(rbPanel, BorderLayout.CENTER);
		
		JPanel optionsPanel = new JPanel(new GridLayout(1, 3, 5, 0));
		optionsPanel.add(startDatePanel);
		optionsPanel.add(endDatePanel);
		optionsPanel.add(sortByPanel);

		setLayout(new BorderLayout(5, 5));
		add(optionsPanel, BorderLayout.NORTH);
		add(tableSPPanel, BorderLayout.CENTER);
		
		refreshTablePanel();
	}
	
	public void refreshTablePanel() {
		tableSPPanel.removeAll();
		getData();
		tableSPPanel.add(tableSP);
		tableSPPanel.revalidate();
	}
	
	private void getData() {
		try {
			if (sortByTypeRB.isSelected()) {
				getDataSortedByType();
				setTable(columnNamesType);
			} else if (sortByDateRB.isSelected()) {
				getDataSortedByDate();
				setTable(columnNamesDateOrVendor);
			}else if (sortByVendorRB.isSelected()) {
				getDataSortedByVendor();
				setTable(columnNamesDateOrVendor);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private void getDataSortedByType() throws SQLException, ClassNotFoundException {
		ArrayList<String[]> totals = db.marketTotalsByType(dateStart, dateEnd);
		data = new String[totals.size()][columnNamesType.length];
		double runningTotal = 0;
		for (int i = 0; i < totals.size(); i++) {
			String[] totalsData = totals.get(i);
			data[i][0] = totalsData[0].substring(5, 7) + "-" 
					+ totalsData[0].substring(8, 10) + "-" 
					+ totalsData[0].substring(0, 4);
			for (int j = 1; j < totalsData.length; j++) {
				if (totalsData[j] == null)data[i][j] = "";
				else data[i][j] = " "+totalsData[j]+" ";
			}
			runningTotal += Double.parseDouble(totalsData[7]);
			data[i][8] = ""+runningTotal;
		}
	}
	
	private void getDataSortedByDate() throws SQLException, ClassNotFoundException {
		ArrayList<String[]> totals = db.marketTotalsByDate(dateStart, dateEnd);
		data = new String[totals.size()][columnNamesDateOrVendor.length];
		boolean subTotalCell = false;
		for (int i = 0; i < totals.size(); i++) {
			String[] totalsData = totals.get(i);
			for (int j = 0; j < totalsData.length; j++) {
				if (j == 0 && totalsData[j] == null) {
					data[i][j] = "["+totalsData[2]+"]" + " SubTotal";
					if (totalsData[2] == null)
						data[i][0] = "[All Dates] Total";
					subTotalCell = true;
				} else if (totalsData[j] == null) {
					data[i][j] = "";
				} else if (j == 3 && subTotalCell) {
					data[i][j] = "["+totalsData[j]+"]";
				} else {
					data[i][j] = " "+totalsData[j]+" ";
				}
			}
			subTotalCell = false;
		}
	}
	
	private void getDataSortedByVendor() throws SQLException, ClassNotFoundException {
		ArrayList<String[]> totals = db.marketTotalsByVendor(dateStart, dateEnd);
		data = new String[totals.size()][columnNamesDateOrVendor.length];
		boolean subTotalCell = false;
		for (int i = 0; i < totals.size(); i++) {
			String[] totalsData = totals.get(i);
			for (int j = 0; j < totalsData.length; j++) {
				if (j == 2 && totalsData[j] == null) {
					data[i][j] = "[Vendor " + totalsData[0] + "] SubTotal";
					if (totalsData[0] == null)
						data[i][2] = "[All Vendors] Total";
					subTotalCell = true;
				} else if (totalsData[j] == null) {
					data[i][j] = "";
				} else if (j == 3 && subTotalCell) {
					data[i][j] = "["+totalsData[j]+"]";
				} else {
					data[i][j] = " "+totalsData[j]+" ";
				}
			}
			subTotalCell = false;
		}
	}
	
	private void setTable(String[] columnNames) {
		table = new JTable(data, columnNames);
		table.setFont(new Font(custFont.getName(), Font.PLAIN, custFont.getSize()-2));
		table.setEnabled(false);
		table.setRowHeight(20);
		table.getTableHeader().setFont(
				new Font(custFont.getName(), Font.PLAIN, custFont.getSize()-1));
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		TableColumnAdjuster tca = new TableColumnAdjuster(table);
		tca.adjustColumns();
		tableSP = new JScrollPane(table);
		tableSP.setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK), 
				BorderFactory.createEmptyBorder(3, 3, 3, 3)));
	}
	
	private void setDatePicker(final JXDatePicker dp, final boolean startingDate) {
		if (startingDate) {
			try {
				String s = db.getEarliestDate();
				int year = Integer.parseInt(s.substring(0, 4));
				int month = Integer.parseInt(s.substring(5, 7)) - 1;
				int day = Integer.parseInt(s.substring(8, 10));
				dp.setDate(new GregorianCalendar(year, month, day).getTime());
				
			} catch (ClassNotFoundException e) {
			} catch (SQLException e) {}
		} else {
			dp.setDate(Calendar.getInstance().getTime());
		}
		dp.setFormats(new SimpleDateFormat("MM / dd / yyyy"));
		dp.getEditor().setEditable(false);
		dp.getEditor().setFont(custFont);
		dp.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent the_event) {
				String s = dp.getEditor().getText().trim();
				String date = s.substring(10, 14) + "-" + s.substring(0, 2) + "-" + s.substring(5, 7);
				if (startingDate) dateStart = date;
				else dateEnd = date;				
				if (datePickerStart.getDate().after(datePickerEnd.getDate())) {
					JOptionPane.showConfirmDialog(null, "Start date is after the end date!", 
							"Warning", JOptionPane.CLOSED_OPTION); 
				}
				refreshTablePanel();
			}
		});
		String s = dp.getEditor().getText().trim();
		String date = s.substring(10, 14) + "-" + s.substring(0, 2) + "-" + s.substring(5, 7);
		if (startingDate) dateStart = date; else dateEnd = date;
	}
	
	private JRadioButton setSortByRB(String name) {
		JRadioButton rb = new JRadioButton(name);
		rb.setFont(custFont);
		rb.setSelected(name.equalsIgnoreCase("Type"));
		rb.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				refreshTablePanel();
			}
		});
		sortByBG.add(rb);
		return rb;
	}
}